import json
from datetime import datetime

from django.forms import model_to_dict
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt

from lianxi20250925.models import category


# Create your views here.
@csrf_exempt
def post_category(request):
    data=json.loads(request.body)
    if data['id']=='' or data['name']=='' or data['desci']=='':
        return JsonResponse(
            {
                'msg':'参数必填'
            }
        )
    if category.objects.filter(name=data['name']).exists() is True and category.objects.filter(id=data['id']) is True:
        return JsonResponse(
            {
                'msg':'id和姓名必须唯一'
            }
        )
    a=category.objects.create(
        id=data['id'],
        name=data['name'],
        desci=data['desci'],
        datet=datetime.now()
    )
    return JsonResponse(
        {
            'msg':'添加成功',
            'item':model_to_dict(a)
        }
    )